import { useState } from 'react';
import { useDispatch } from 'react-redux';
import { addTodo } from '../store/actions/todos';

export const TodoHeader = () => {
  const dispatch = useDispatch();

  // 定义组件状态
  const [txt, setTxt] = useState('xxx');

  // todo 输入变化事件
  const handleTxtInput = (e) => {
    console.log(e.target.value);
    setTxt(e.target.value);
  };
  // addto 事件处理函数
  const handleAddTodo = (e) => {
    console.log(e.keyCode);
    // 13是回车按钮
    if (e.keyCode !== 13) return;
    if (!txt.trim()) return;

    const addTodoAction = addTodo(txt);
    console.log('addtodo action', addTodoAction);

    // payload: "aadfadsf"
    // "aadfadsf"要发送给服务器=>服务器响应=>200
    // 下一步才会把数据更新到页面中
    // payload: "aadfadsf"
    // type: "todos/add"

    // axios.post
    // post 成功

    dispatch(addTodo(txt));
    setTxt('');
  };

  return (
    <header className="header">
      <h1>todos</h1>
      <input
        className="new-todo"
        placeholder="What needs to be done?"
        autoFocus
        value={txt}
        onChange={handleTxtInput}
        onKeyDown={handleAddTodo}
      />
    </header>
  );
};
